package com.warm.pump.frame.util;

import com.warm.pump.module.sys.bean.po.gen.DictItem;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by guozj on 2016/10/13.
 */
public class SpringBeanUtil {
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }


    public static List<DictItem> getServiceBeans(String... basePackages) {
        List<DictItem> beanList = new ArrayList<>();
        Map<String, Object> beansWithAnnotationMap = applicationContext.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
        Class<? extends Object> clazz ;
        for (Map.Entry<String, Object> entry : beansWithAnnotationMap.entrySet()) {
            clazz = entry.getValue().getClass();//获取到实例对象的class信息
            String className = clazz.getName();
            for (String packageName : basePackages) {
                if (className.startsWith(packageName)) {
                    DictItem item = new DictItem();
                    item.setDictCode(entry.getKey());
                    item.setDictName(entry.getKey());
                    beanList.add(item);
                }
            }
        }
        return beanList;
    }

    public static List<DictItem> getMethodsByBeanName(String beanName) {
        List<DictItem> beanList = new ArrayList<>();
        Map<String, Object> beansWithAnnotationMap = applicationContext.getBeansWithAnnotation(org.springframework.stereotype.Service.class);
        Object o = beansWithAnnotationMap.get(beanName);
        Class<? extends Object> clazz = o.getClass();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            DictItem item = new DictItem();
            item.setDictCode(method.getName());
            item.setDictName(method.getName());
            beanList.add(item);
        }
        return beanList;
    }


    public static <T> T getBean(Class<T> tClass) {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(tClass);
    }

    public static <T> T getBean(String beanName, Class<T> tClass) {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(beanName, tClass);
    }

    public static <T> T getBean(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(beanName);
    }
}
